package com.jsch.test.sshd;

import org.apache.sshd.common.file.virtualfs.VirtualFileSystemFactory;
import org.apache.sshd.server.SshServer;
import org.apache.sshd.server.auth.password.PasswordAuthenticator;
import org.apache.sshd.server.channel.ChannelSession;
import org.apache.sshd.server.command.Command;
import org.apache.sshd.server.command.CommandFactory;
import org.apache.sshd.server.config.keys.DefaultAuthorizedKeysAuthenticator;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.shell.InteractiveProcessShellFactory;
import org.apache.sshd.server.shell.ProcessShellFactory;
import org.apache.sshd.sftp.server.SftpSubsystemFactory;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class SshdServer {
    public static void main(String[] args) {
        //创建SshServer对象
        SshServer sshd = SshServer.setUpDefaultServer();
        //配置端口
        sshd.setPort(2222);
        //设置默认的签名文件，如过文件不存在会创建
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("/Users/chaoxing.hou/myfile/test")));
        //设置用户名和密码进行登录验证
        sshd.setPasswordAuthenticator((username, password, serverSession) -> {
            //假定用户名：usera 密码：apass，
            //这里可以增加逻辑从数据库或其他方式校验用户名和密码
            //返回true则校验成功否则失败
            System.out.println("登录验证：" + username + "," + password);
            return "root".equals(username) && "admin".equals(password);
        });
        //设置sftp子系统
        sshd.setSubsystemFactories(Arrays.asList(new SftpSubsystemFactory()));
        //设置sftp默认的访问目录
        Path dir = Paths.get("/Users/chaoxing.hou");
        sshd.setFileSystemFactory(new VirtualFileSystemFactory(dir.toAbsolutePath()));
        //设置ssh的shell环境
        sshd.setShellFactory(InteractiveProcessShellFactory.INSTANCE);
        //启动ssh服务
        try {
            sshd.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //保持java进程不关闭
        Object obj = new Object();
        synchronized (obj) {
            try {
                obj.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main1(String[] args) {
        SshServer sshd = SshServer.setUpDefaultServer();
        sshd.setPort(22);

        //*give host key generator a path, when sshd server restart, the same key will be load and used to authenticate the server
        sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get("hostkey.ser")));

        sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
            @Override
            public boolean authenticate(String username, String password, ServerSession session) {
                System.out.println("authen:  user=" + username + "  password=" + password);
                if ("bellring".equals(username) && "123456".equals(password))
                    return true;
                return false;
            }
        });

        //use file ~/.ssh/authorized_keys
        sshd.setPublickeyAuthenticator(new DefaultAuthorizedKeysAuthenticator(false));

        //* CommandFactory can be userd in addition to the ShellFactory,
        //*  it can also be used instead of the ShellFactory.
        //*  The CommandFactory is used when direct commands are sent to the SSH server,
        //*  as this is the case when running ssh localhost shutdown or scp xxx
//        ScpCommandFactory scpCmdFactory = new ScpCommandFactory();
//        scpCmdFactory.setDelegateCommandFactory(new CommandFactory() {
//            public Command createCommand(String command) {
//                System.out.println("command = \"" + command + "\"");
//                return new ProcessShellFactory(("cmd /c " + command).split(" ")).create();
//            }
//        });
//        sshd.setCommandFactory(new CommandFactory() {
//            @Override
//            public Command createCommand(ChannelSession channelSession, String command) throws IOException {
//                return new ProcessShellFactory(("cmd /c " + command).split(" ")).create();
//            }
//        });

//        sshd.start();
    }
}
